<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/3/3
 * Time: 下午4:48
 */

namespace app\merchant\controller;


use Alipay\Alipayobj;
use app\common\model\Agent;
use app\common\model\CardMember;
use app\common\model\Merchant;
use think\Controller;

class Alicardstest extends Controller
{
    public function opencardlq()
    {
//echo 123;
        $acinfo=$this->getuserinfo(request()->get('auth_code'));

        $params['access_token']=$acinfo['access_token'];
        $params['template_id']=request()->get('template_id');
        $params['request_id']=request()->get('request_id');
        $content = $this->activateform_query($params);
        $params2=$params;
        $params2['uid']=$acinfo['user_id'];
        $params2['infos']=json_decode($content['data']['infos'],true);

        $card=$this->card_open($params2);
        var_dump($card);
        exit();

    }
    public function card_open($param){

        $datas['merchid'] = 501;
        $User = new Merchant();
        $Agent = new Agent();

        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.open";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['auth_token']=$param['access_token'];

        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_serial_no' => date('YmdHis').rand(10000,99999),
            'card_template_id'=>$param['template_id'],
            'card_user_info'=>array(
                'user_uni_id'=>$param['uid'],
                'user_uni_id_type'=>"UID",
            ),
            'card_ext_info'=>array(
                'external_card_no'=>date('Ymdhis').rand(1000,9999),
              'open_date'=>date('Y-m-d H:i:s'),
              'valid_date'=>"2020-12-12 23:59:59",
            ),
//            'member_ext_info'=>array(
//                'name'=>$param['infos'][1]['OPEN_FORM_FIELD_NAME'],
//                'cell'=>$param['infos'][0]['OPEN_FORM_FIELD_MOBILE'],
//            ),

        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
//return $data;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        return $content;
    }

    //查询用户提交的会员卡表单信息
    public function activateform_query($param)
    {

        $datas['merchid'] = 501;

        $User = new Merchant();
        $Agent = new Agent();

        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.activateform.query";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['auth_token']=$param['access_token'];

        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'biz_type' => "MEMBER_CARD",
            'template_id' => $param['template_id'],
            "request_id" => $param['request_id'],
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;

        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);

        if($content['alipay_marketing_card_activateform_query_response']['code']==10000){
            $info['code']=0;
            $info['data']['infos']=$content['alipay_marketing_card_activateform_query_response']['infos'];
        }else{
            $info['code']=$content['alipay_marketing_card_activateform_query_response']['code'];
            $info['message']=$content['alipay_marketing_card_activateform_query_response']['msg'];
        }
return $info;


    }
    //获取用户userid
    public function getuserinfo($code="e2691129a3424fa696921ac1a56fRX10"){
        $datas['merchid'] = 501;

        $User = new Merchant();
        $Agent = new Agent();

        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.system.oauth.token";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['app_auth_token'] = $users['ali_merid'];
        $data['grant_type'] = 'authorization_code';
        $data['code'] = $code;
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");

        $data['sign'] = $signContent;

        $uid = $aliObj->getuid($data);

        $user = json_decode($uid, true);
        $params['user_id']=$user['alipay_system_oauth_token_response']['user_id'];
        $params['access_token']=$user['alipay_system_oauth_token_response']['access_token'];
        return $params;

    }

    //上传图片
    public function upload_img($source_url = "")
    {
        $data['merchid'] = 501;
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $data['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $source_url = "/uploads/card/20180303/42983fbd1d0dd4e1b8cbba6e27d5b5df.jpg";
        $info = pathinfo($source_url);
        $aliObj = new Alipayobj($options);
        $data2['app_id'] = $agent['ali_app_id'];
        $data2['method'] = "alipay.offline.material.image.upload";
        $data2['charset'] = "UTF-8";
        $data2['sign_type'] = "RSA2";
        $data2['timestamp'] = date('Y-m-d H:i:s');
        $data2['version'] = "1.0";
        $data2['app_auth_token'] = $users['ali_merid'];
        $data2['image_type'] = $info['extension'];
        $data2['image_name'] = $info['filename'];
        $data2['image_content'] = "@" . $source_url;
        $signContent = $aliObj->rsaSign($data2, $signType = "RSA2");
        $data2['sign'] = $signContent;
        $sj = $aliObj->upload_file($data2);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        $repson = $content['alipay_offline_material_image_upload_response'];
        if ($repson['code'] == "10000") {
            $msg['code'] = 0;
            $msg['data']['image_url'] = $repson['image_url'];
            $msg['data']['image_id'] = $repson['image_id'];
        } else {
            $msg['code'] = $repson['code'];
            $msg['message'] = $repson['msg'];
        }
        var_dump($msg);
        exit();
        return $msg;
    }

    //创建会员卡
    public function create_card()
    {

        $datas['merchid'] = 501;
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $CardMember = new CardMember();
        $cardinfo = $CardMember->where(array('id' => 138))->find();
        $img_logo = $this->upload_img($cardinfo['logo_url_abs']);
        $img_bg = $this->upload_img($cardinfo['bg_url_abs']);

        //卡片信息
        $template_style_info = array(
            "card_show_name" => "智慧商圈",
            "logo_id" => $img_bg['data']['image_id'],//logo图片
            "background_id" => $img_bg['data']['image_id'],//背景图片
            "bg_color" => "rgb(55,112,179)",//背景色（rgb）
        );
        //权益信息
        $template_benefit_info = array(
            "title" => "测试",//权益描述
            "benefit_desc" => "测试",//权益描述信息
            "start_date" => "2016-07-18 15:17:23",//开始时间
            "end_date" => "2020-07-18 15:17:23",//权益结束时间


        );
        $field_rule_list = array(
            array(
                'field_name' => 'Balance',
                'rule_name' => 'ASSIGN_FROM_REQUEST',
                'rule_value' => 'Balance'
            ),
//            array(
//                'field_name' => 'Point',
//                'rule_name' => 'ASSIGN_FROM_REQUEST',
//                'rule_value' => 'Point'
//            ),
//            array(
//                'field_name' => 'Level',
//                'rule_name' => 'ASSIGN_FROM_REQUEST',
//                'rule_value' => 'Level'
//            ),
        );
        //栏位信息
        $column_info_list = array(
            array(
                'code' => 'BALANCE',//BALANCE：会员卡余额  POINT：积分LEVEL：等级TELEPHONE：联系方式自定义栏位：行为由商户定义，自定义Code码（只要无重复）
                'operate_type' => 'staticinfo',//1、openNative：打开二级页面，展现 more中descs  2、openWeb：打开URL 3、staticinfo：静态信息注意：不填则默认staticinfo；标准code尽量使用staticinfo，例如TELEPHONE商家电话栏位就只支持staticinfo；
                'title' => '余额'
            ),
//            array(
//                'code' => 'LEVEL',//BALANCE：会员卡余额  POINT：积分LEVEL：等级TELEPHONE：联系方式自定义栏位：行为由商户定义，自定义Code码（只要无重复）
//                'operate_type' => 'staticinfo',//1、openNative：打开二级页面，展现 more中descs  2、openWeb：打开URL 3、staticinfo：静态信息注意：不填则默认staticinfo；标准code尽量使用staticinfo，例如TELEPHONE商家电话栏位就只支持staticinfo；
//                'title' => '等级'
//            ),
//            array(
//                'code' => 'POINT',//BALANCE：会员卡余额  POINT：积分LEVEL：等级TELEPHONE：联系方式自定义栏位：行为由商户定义，自定义Code码（只要无重复）
//                'operate_type' => 'staticinfo',//1、openNative：打开二级页面，展现 more中descs  2、openWeb：打开URL 3、staticinfo：静态信息注意：不填则默认staticinfo；标准code尽量使用staticinfo，例如TELEPHONE商家电话栏位就只支持staticinfo；
//                'title' => '积分',
//            ),

        );
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.template.create";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['notify_url'] = 'https://os.wunengkeji.com/';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            "request_id" => date("YmdHis") . rand(1000, 9999),
            "card_type" => "OUT_MEMBER_CARD",
//            "biz_no_prefix" => "HY-",
            "biz_no_suffix_len" => "12",
            "write_off_type" => "qrcode",
            "template_style_info" => $template_style_info,
            "column_info_list" => $column_info_list,
            "field_rule_list" => $field_rule_list,
            //   "template_benefit_info"=>$template_benefit_info,

        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        $template_id = $content['alipay_marketing_card_template_create_response']['template_id'];
        if ($content['alipay_marketing_card_template_create_response']['code'] == 10000) {
            $params['code'] = 0;
            $params['data']['template_id'] = $template_id;

        } else {
            $params['code'] = $content['alipay_marketing_card_template_create_response']['code'];
            $params['data']['msg'] = $content['alipay_marketing_card_template_create_response']['msg'];;
        }
        return json($params);

    }
    //会员卡开卡填写信息
    //必选字段
    /*
     * 表单必填字段配置，common_fields属性定义一个表单字段数组，字段有效值如下列表所示：
        OPEN_FORM_FIELD_MOBILE -- 手机号
        OPEN_FORM_FIELD_GENDER -- 性别
        OPEN_FORM_FIELD_NAME -- 姓名
        OPEN_FORM_FIELD_BIRTHDAY -- 生日（不含年份，如：01-01）
        OPEN_FORM_FIELD_BIRTHDAY_WITH_YEAR -- 生日（含年份，如：1988-01-01）
        OPEN_FORM_FIELD_IDCARD -- 身份证
        OPEN_FORM_FIELD_CERT_TYPE -- 证件类型
        OPEN_FORM_FIELD_CERT_NO -- 证件号
        OPEN_FORM_FIELD_EMAIL -- 邮箱
        OPEN_FORM_FIELD_ADDRESS -- 地址
        OPEN_FORM_FIELD_CITY -- 城市
        OPEN_FORM_FIELD_IS_STUDENT -- 是否学生认证
        OPEN_FORM_FIELD_MEMBER_GRADE -- 会员等级

        注：
        1. 会员等级、是否学生认证字段，如果获取不到该项数据时，表单页面不做展示。
        2. 身份证字段和证件号、证件类型字段不可同时配置。
        3. 如果身份证字段不能满足业务需求，可通过配置证件类型+证件号字段来获取其他证件类型的支持，目前支持的证件类型有：身份证、护照、港澳居民通行证、台湾居民通行证
                 * */
    public function card_open_info()
    {

        $datas['merchid'] = 501;

        $User = new Merchant();
        $Agent = new Agent();

        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.formtemplate.set";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'template_id' => '20180308000000000843325000300945',
            'fields' => array(
                'required' => array(
                    'common_fields' => array('OPEN_FORM_FIELD_NAME', 'OPEN_FORM_FIELD_MOBILE')
                )
            ),

        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;

        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);

        if ($content['alipay_marketing_card_formtemplate_set_response']['code'] = 10000) {
            $params['code'] = 0;
            $params['message'] = "设置成功";

        } else {
            $params['code'] = $content['alipay_marketing_card_formtemplate_set_response']['code'];
            $params['message'] = "设置失败";
        }
        return json($params);


    }

    //获取会员卡领卡投放链接
    public function card_activateurl()
    {

        $datas['merchid'] = 501;

        $User = new Merchant();
        $Agent = new Agent();

        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.activateurl.apply";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'template_id' => '20180308000000000843325000300945',
            "callback" => $http_type . $_SERVER['HTTP_HOST'] . url('Alicardstest/opencardlq'),
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;

        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        if ($content['alipay_marketing_card_activateurl_apply_response']['code'] == 10000) {
            $params['code'] = 0;
            $params['data']['url'] = urldecode($content['alipay_marketing_card_activateurl_apply_response']['apply_card_url']);

        } else {
            $params['code'] = $content['alipay_marketing_card_activateurl_apply_response']['code'];
            $params['data']['msg'] = $content['alipay_marketing_card_activateurl_apply_response']['msg'];;
        }

        return $params;


    }

}